package com.aimusic.interceptor;

import com.aimusic.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component // 让Spring扫描为Bean
@Slf4j
public class ChatHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手前执行：验证用户并传递userId到处理器
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 转换为HTTP请求，获取TokenFilter中已验证的userId
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();

            // 关键：从request中获取TokenFilter验证后的userId（安全可靠）
            Integer userId = CurrentHolder.getCurrentId();
            if (userId == null) {
                // 无有效userId（Token无效或未登录），拒绝握手
                log.warn("请求: {} 未登录，拒绝握手", httpRequest.getRequestURI());
                return false;
            }

            // 将userId存入会话属性，供后续Handler使用
            attributes.put("userId", userId.toString()); // 转为字符串，避免类型问题
            return true; // 允许握手
        }
        return false; // 非HTTP请求，拒绝握手
    }

    /**
     * 握手后执行：无需处理
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        // 空实现
    }
}
